package com.dragon.app.ykd.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.dragon.app.commons.dto.WithholdDTO;
import com.dragon.app.commons.utils.UserUtils;
import com.dragon.app.commons.vo.JsonResult;
import com.dragon.app.marvel2.NewMarvelCoreService;
import com.dragon.app.ykd.dto.RepaymentNoMobileDTO;
import com.dragon.common.repository.mybatis.paginator.domain.Order;
import com.dragon.common.repository.mybatis.paginator.domain.PageBounds;
import com.dragon.core.service.MpPaymentWithholdLogIService;
import com.dragon.loan.entity.AcLoanApplyInfo;
import com.dragon.loan.repository.AcLoanApplyInfoRepository;
import com.fintech.user.entity.RealNameAuthentication;
import com.fintech.user.entity.User;
import com.fintech.user.service.RealNameAuthenticationService;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.dto.MarvelsApiResultDTO;
import com.marvels.common.exception.MarvelsApiBusinessException;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.loan.dto.ShouldRepaymentDTO;
import com.marvels.financial.loan.service.ReimbursementProcessService;
import com.marvels.financial.pay.service.PayService;

import cn.hutool.core.bean.BeanUtil;

@Service("clientRepaymentAppService")
public class ClientRepaymentServiceImpl implements ClientRepaymentService{
	@Autowired
	private RealNameAuthenticationService realNameAuthenticationService;
	@Autowired
    private MpPaymentWithholdLogIService mpPaymentWithholdLogIService;
	@Autowired
	private NewMarvelCoreService newMarvelCoreService;
	@Autowired
	private ReimbursementProcessService reimbursementProcessService;
	@Autowired
	private PayService payService;
	@Autowired
	private AcLoanApplyInfoRepository acLoanApplyInfoRepository;
	/**
	 * 获取还款信息（新版本）
	 *
	 * @return
	 */
	@Override
	public JsonResult getRepaymentInfoNew(String loanId,String accessToken,String idFintechUmUser) {
		JsonResult<List<ShouldRepaymentDTO>> jsonResult = new JsonResult<List<ShouldRepaymentDTO>>();
		MarvelsLogUtil.getInstance().info("start getRepaymentInfoNew param is [loanId="+loanId+"][accesstoken =" + accessToken + "]"+ "[idFintechUmUser="+idFintechUmUser+"]");

		try {
			//1 查询用户信息及实名认证信息
			User user = UserUtils.getUser(accessToken, idFintechUmUser);
			if (user == null) {
				jsonResult.setErrorCode(9999);
				jsonResult.setMessage("登录超时，请重新登录！");
				return jsonResult;
			}
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(user.getId());
			if (realNameAuthentication == null) {
				jsonResult.setErrorMsg("您没有实名认证!");
				return jsonResult;
			}

			if(StringUtils.isBlank(loanId)) {
				List<Order> orderList = new ArrayList<Order>();
				PageBounds pageBounds = new PageBounds(1, 1000, orderList);
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("custIdCard",realNameAuthentication.getIdentityCardNo());
				paramMap.put("loanStatus", LoanStateConstant.D01.toString());
				List<AcLoanApplyInfo> resultList = acLoanApplyInfoRepository.queryLoanInfoByCondition(paramMap, pageBounds);
				if(CollectionUtils.isNotEmpty(resultList)) {
					loanId = resultList.get(resultList.size()-1).getLoanId();
				}
			}

			com.marvels.financial.loan.dto.RepaymentNoMobileDTO searchRepaymentParam = new com.marvels.financial.loan.dto.RepaymentNoMobileDTO();
			searchRepaymentParam.setCustCardNo(realNameAuthentication.getIdentityCardNo());
			searchRepaymentParam.setLoanId(loanId);
			List<ShouldRepaymentDTO> data = reimbursementProcessService.selectPaymentInformation(searchRepaymentParam);
			jsonResult.setData(data);
			return jsonResult;
			//return newMarvelCoreService.getForObjectPostRepayment(MarvelURLConstant.FINANCIAL_PROCESS_API_SELECTPAYMENTINFORMATION, searchRepaymentParam, List.class);
		}catch(Exception ex){
			jsonResult.setErrorMsg("获取数据失败!");
			MarvelsLogUtil.getInstance().error("ClientRepaymentServiceImpl call getRepaymentInfoNew==>>", ex);
		}
		return jsonResult;
	}

	@Override
	public JsonResult<String> repaymentNoMobile( WithholdDTO withholdDTO, String accessToken, String idFintechUmUser){
		JsonResult<String> jsonResult = new JsonResult<String>();

//		if(withholdDTO.getPlanId()==null){
//			jsonResult.setErrorMsg("还款信息错误，请稍后重试!");
//			return jsonResult;
//		}

		com.marvels.financial.loan.dto.RepaymentNoMobileDTO repaymentNoMobileDTO = new com.marvels.financial.loan.dto.RepaymentNoMobileDTO();
		repaymentNoMobileDTO.setLoanId(withholdDTO.getMerchantTreatyNo());
		repaymentNoMobileDTO.setPayType(withholdDTO.getPayType());
		repaymentNoMobileDTO.setPlanCode(withholdDTO.getPlanId() == null ? null : withholdDTO.getPlanId().toString());
		repaymentNoMobileDTO.setUserBankId(withholdDTO.getId());
		repaymentNoMobileDTO.setS1PayerName(withholdDTO.getS1PayerName());//姓名
		repaymentNoMobileDTO.setS3PayerCardNo(withholdDTO.getS3PayerCardNo());//身份证
		repaymentNoMobileDTO.setS4PayerBankCardNo(withholdDTO.getS4PayerBankCardNo());//银行卡号
		repaymentNoMobileDTO.setS7BankMobile(withholdDTO.getS7BankMobile());//手机号
		repaymentNoMobileDTO.setT2SmsCode(withholdDTO.getT2SmsCode());//验证码
		repaymentNoMobileDTO.setBankName(withholdDTO.getBankName());//银行名称
		repaymentNoMobileDTO.setWithholdWay(withholdDTO.getWithholdWay());// 0 协议代扣  1 直接代扣(四要素代扣)
		repaymentNoMobileDTO.setWithholdCategory(withholdDTO.getWithholdCategory());//代扣类别 1 扣还款计划金额  2 扣展期费
		repaymentNoMobileDTO.setType(withholdDTO.getExtensionType());//1: 1天  2:3天  3:7天
		repaymentNoMobileDTO.setAmount(withholdDTO.getAmount());
		try {
			MarvelsApiResultDTO result = reimbursementProcessService.repaymentNoMobile(repaymentNoMobileDTO);
			jsonResult.setErrorCode(Integer.parseInt(result.getCode()));
			jsonResult.setMessage(result.getMessage());
		} catch (MarvelsApiBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>提交还款FAIL:", e);
			jsonResult.setErrorCode(-2);
			jsonResult.setMessage(e.getMessage());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>提交还款", e);
			jsonResult.setErrorCode(-2);
			jsonResult.setMessage("提交还款异常");
		}
		return jsonResult;
		//return newMarvelCoreService.getForObjectPostRepayment(MarvelURLConstant.FINANCIAL_PROCESS_API_REPAYMENTNOMOBILE, repaymentNoMobileDTO, String.class);
	}

	//还款记录
	@Override
	public JsonResult repaymentRecord(Integer pageIndex,Integer pageSize, String accessToken, String idFintechUmUser){
		JsonResult<List<Map<String,Object>>> result = new JsonResult<List<Map<String,Object>>>();
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			result.setErrorCode(9999);
			result.setMessage("登录超时，请重新登录！");
			return result;
		}
		RealNameAuthentication realName = realNameAuthenticationService.queryByUserId(user.getId());
		if(null==realName){
			result.setErrorCode(-2);
			result.setMessage("此用户还未认证");
			return result;
		}
		// 判断是否走新核心系统接口
		boolean marvelStart = newMarvelCoreService.isMarvelStart(realName.getIdentityCardNo(), null);
		if(marvelStart){
			com.marvels.financial.loan.dto.RepaymentNoMobileDTO repaymentNoMobileDTO = new com.marvels.financial.loan.dto.RepaymentNoMobileDTO();
			repaymentNoMobileDTO.setUserId(user.getId());
			List<Map<String,Object>> listMap =  reimbursementProcessService.selectRepaymentHistory(repaymentNoMobileDTO);
			result.setData(listMap);
			return result;
			/*UserIdDTO userIdDTO = new UserIdDTO();
			userIdDTO.setUserId(user.getId());
			return newMarvelCoreService.getForObjectPostRepayment(MarvelURLConstant.FINANCIAL_PROCESS_API_SELECTREPAYMENTHISTORY, userIdDTO, List.class);*/
		}
		List<Map<String,Object>> list = mpPaymentWithholdLogIService.returnList(realName.getIdentityCardNo(), null);
		result.setData(list);
		return result;
	}

	@Override
	public JsonResult<String> directPaymentSms( RepaymentNoMobileDTO repaymentNoMobileDTO, String accessToken, String idFintechUmUser){
		JsonResult<String> jsonResult = new JsonResult<String>();
		com.marvels.financial.loan.dto.RepaymentNoMobileDTO param = new com.marvels.financial.loan.dto.RepaymentNoMobileDTO();
		BeanUtil.copyProperties(repaymentNoMobileDTO, param);
		try {
			Map<String, Object> map = payService.directPaymentSms(param);
			jsonResult.setErrorCode(0);
			jsonResult.setMessage("成功");
			jsonResult.setData(JSONObject.toJSONString(map));
		} catch(MarvelsBusinessException e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>直接支付短信调用失败", e);
			jsonResult.setMessage(e.getMessage());
			jsonResult.setErrorCode(-1);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>直接支付短信调用异常", e);
			jsonResult.setMessage("提交还款异常");
			jsonResult.setErrorCode(-2);
		}
		return jsonResult;
		//return newMarvelCoreService.getForObjectPostRepayment(MarvelURLConstant.FINANCIAL_PROCESS_API_DIRECTPAYMENTSMS, repaymentNoMobileDTO, String.class);
	}

	/* (non-Javadoc)
	 * @see com.dragon.app.ykd.service.ClientRepaymentService#getCustAllPaymentPlan(java.lang.String, java.lang.String)
	 */
	@Override
	public JsonResult<List<Map<String, Object>>> getCustAllPaymentPlan(String accessToken, String idFintechUmUser) {

		return null;
	}
}
